  /*
  * MinIO Cloud Storage (C) 2018 MinIO, Inc.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  *
  *     http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */

  import React from "react";
  import { createStyles, makeStyles, withStyles, Theme } from '@material-ui/core/styles';
  import ReactEcharts from 'echarts-for-react';
  import Alert from '@material-ui/lab/Alert';
  import IconButton from '@material-ui/core/IconButton';
  import Collapse from '@material-ui/core/Collapse';
  import CloseIcon from '@material-ui/icons/Close';
  import api from "../../../common/api";
  import { ChartUrl, beforeNowtimeByMinu } from "./types";

const styles = (theme: Theme) =>
  createStyles({
    alert: {
      position: "absolute",
      width: "100%",
      textAlign: "center",
      zIndex: 1000, 
      top: 35
    },
    alertPop: {
      margin: "0 auto",
      width: "130px"
    },
    chart: {
      height: '285px !important', 
      width: '100%', 
      marginTop: -20,
      marginBottom: -40
    },
});

interface ChartState {
  classes: any;
  inputStep: string,
}
export class ChartMem extends React.Component<ChartState, any> {
  constructor(props:any){
    super(props);
    this.state = {
      loading: false,
      msg:"",
      dataWarn:"",
      step: "14",
      open: false
    };
  };
  setOpen(a:boolean){
    this.setState({
      open: a
    })
  }
  getChart(step:any) {
    // 节点内存使用率 (centos7)
    // node_memory_MemFree_bytes
    // node_memory_MemAvailable_bytes
    // node_memory_MemTotal_bytes
    // let url = ChartUrl+"(1-node_memory_MemAvailable_bytes/node_memory_MemTotal_bytes)*100&start="+Date.parse(beforeNowtimeByMinu(30)).toString().substring(0,10)+"&end="+Date.parse(beforeNowtimeByMinu(0)).toString().substring(0,10)+"&step=14";
    let duration = 60;
    if(step == '1'){
      duration = 15
    }else if(step == '7'){
      duration = 30
    }else if(step == '14'){
      duration = 60
    }else if(step == '28'){
      duration = 120
    }else if(step == '86'){
      duration = 360
    }else if(step == '172'){
      duration = 720
    }else if(step == '345'){
      duration = 1440
    }
    // 內存已用 GB
    let url = ChartUrl+"(node_memory_MemTotal_bytes-node_memory_MemAvailable_bytes)/(1024*1024*1024)&start="+Date.parse(beforeNowtimeByMinu(duration)).toString().substring(0,10)+"&end="+Date.parse(beforeNowtimeByMinu(0)).toString().substring(0,10)+"&step="+step;
    api
      .invoke("GET", url)
      .then((res) => {
        var rootData = res.data.result;
        if(rootData != []){
          for(var i=0;i<rootData.length;i++){
            for(var a=0;a<rootData[i].values.length;a++){
              rootData[i].values[a][1] = parseFloat(rootData[i].values[a][1]);
              rootData[0].values[a][1] += rootData[i].values[a][1]
            }
          }
          // for(var i=1;i<rootData.length;i++){
          //   for(var a=0;a<rootData[i].values.length;a++){
          //     rootData[0].values[a][1] += rootData[i].values[a][1]
          //   }
          // }
          var x = rootData[0].values.length-1
          var length = rootData.length
          console.log(rootData[0])
          this.setState({
            memUsed: parseFloat((rootData[0].values[x][1]/length).toFixed(2)),
          });
        }else{
          this.setState({
            dataWarn: "暂无数据",
            loading: false 
          })
          this.setOpen(true);
        }
      })
      .catch(err => {
        this.setState({
          dataWarn: "暂无数据",
          loading: false 
        })
        this.setOpen(true);
      });
    // 內存剩余 GB
    let url2 = ChartUrl+"node_memory_MemAvailable_bytes/(1024*1024*1024)&start="+Date.parse(beforeNowtimeByMinu(duration)).toString().substring(0,10)+"&end="+Date.parse(beforeNowtimeByMinu(0)).toString().substring(0,10)+"&step="+step;
    api
      .invoke("GET", url2)
      .then((res) => {
        var rootData2 = res.data.result;
        if(rootData2 != []){
          for(var i=0;i<rootData2.length;i++){
            for(var a=0;a<rootData2[i].values.length;a++){
              rootData2[i].values[a][1] = parseFloat(rootData2[i].values[a][1]);
              rootData2[0].values[a][1] += rootData2[i].values[a][1]
            }
          }
          // for(var i=1;i<rootData2.length;i++){
          //   for(var a=0;a<rootData2[i].values.length;a++){
          //     rootData2[0].values[a][1] += rootData2[i].values[a][1]
          //   }
          // }
          var x = rootData2[0].values.length-1
          var length = rootData2.length
          console.log(rootData2[0])
          this.setState({
            memAvailable: parseFloat((rootData2[0].values[x][1]/length).toFixed(2)),
          });
        }else{
          this.setState({
            dataWarn: "暂无数据",
            loading: false 
          })
          this.setOpen(true);
        }
      })
      .catch(err => {
        this.setState({
          dataWarn: "暂无数据",
          loading: false 
        })
        this.setOpen(true);
      });
  }
  componentDidMount(): void {
    var that = this
    that.getChart(that.state.step);
  }
  componentDidUpdate(prevProps:any): void {
    if(prevProps.inputStep !== this.state.step){
        this.getChart(this.state.step);
        var timer = setInterval(() => {
          let url = window.location.href
          if(url.indexOf("/dashboard") != -1){
            this.getChart(this.state.step);
          }else{
            clearInterval(timer)
          }
        }, 25000)
    }
  }
  static getDerivedStateFromProps(nextProps:any, prevState:any) {
    // 当传入的type发生变化的时候，更新state
    if (nextProps.inputStep !== prevState.step) {
      return {
        step: nextProps.inputStep
      }
    }
    // 否则，对于state不进行任何操作
    return null;
  }
  getOption= () => ({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c}GB ({d}%)'
    },
    color: ['#91c7ae', '#5793f3'],
    legend: {
        bottom: '20',
        data: ['已用', '剩余']
    },
    series: [
      {
        name: '平均内存',
        type: 'pie',
        startAngle:120,
        radius: '55%',
        center: ['50%', '45%'],
        label: {
          formatter: '{b} {d}%',
        },
        data: [
          {value: this.state.memUsed, name: '已用', selected: true},
          {value: this.state.memAvailable, name: '剩余'},
        ]
      }
    ]
  });
  render() {
    const { classes } = this.props;
    return (
      <div style={{position: "relative"}}>
        {this.state.open ? (
        <div className={classes.alert}>
          <Collapse in={this.state.open} className={classes.alertPop}>
            <Alert severity="error" style={{padding: "0 16px"}}>
              {this.state.dataWarn}
            </Alert>
          </Collapse>
        </div>
        ):(
          <ReactEcharts
          ref="chart"
          option={this.getOption()}
          className={classes.chart}/>
          )}
      </div>
    );
  }
};
export default withStyles(styles)(ChartMem)